package com.ybkj.o2o.zhuanche.manager.impl;

import com.ybkj.o2o.zhuanche.entity.Insurance;
import com.ybkj.o2o.zhuanche.service.InsuranceService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ybkj.o2o.zhuanche.common.DataGrid;
import com.ybkj.o2o.zhuanche.common.query.Car2Query;
import com.ybkj.o2o.zhuanche.common.query.CarQuery;
import com.ybkj.o2o.zhuanche.entity.Car;
import com.ybkj.o2o.zhuanche.entity.CarType;
import com.ybkj.o2o.zhuanche.entity.CarTypeCompany;
import com.ybkj.o2o.zhuanche.manager.CarManager;
import com.ybkj.o2o.zhuanche.service.CarService;
import com.ybkj.o2o.zhuanche.service.CarTypeCompanyService;
import com.ybkj.o2o.zhuanche.service.CarTypeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class DefaultCarManager implements CarManager {
  
  @Autowired
  private CarService carService;

  @Autowired
  private CarTypeCompanyService carTypeCompanyService;

  @Autowired
  private CarTypeService carTypeService;

  @Autowired
  private InsuranceService insuranceService;

  @Override
  public Car findByCarId(Long carId, String appKey) {
    Car car = carService.findByCarId(carId, appKey);
    if (null != car) {
      CarType carType = carTypeService.findByCarTypeId(car.getCarTypeId(), appKey);
      if (null != carType) {
        car.setCarTypeName(carType.getTypeName());
      }
      List<Insurance> ins = insuranceService.findByCarId(car.getId(), appKey);
      if(!CollectionUtils.isEmpty(ins)){
        car.setInsuranceTime(ins.get(0).getInsuranceEndDate());
      }
    }
    return car;
  }


  @Override
  @Transactional(rollbackFor = Exception.class)
  public Car save(Car car) {
    if (car.getEmployId() != null) {
      Car car2 = carService.findByEmployId(car.getEmployId(), car.getAppKey());
      if (car2 != null) {
        car2.setEmployId(null);
        car2.setEmployName(null);
        carService.update(car2);
      }
    }
    int rowCount = carService.insert(car);
    if (rowCount != 1) {
      throw new RuntimeException("创建车辆失败");
    }
    return car;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteById(Long id, String appKey) {
    int rowCount = carService.deleteById(id, appKey);
    if (rowCount != 1) {
      throw new RuntimeException("删除车辆失败");
    }
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void update(Car car, Long oldEmployId) {
    car.setUpdated(new Date());
    if (oldEmployId != null && "-".equals(car.getEmployName())) {
      Car car1 = carService.findByEmployId(oldEmployId, car.getAppKey());
      if (car1 != null) {
        car1.setEmployId(null);
        car1.setEmployName(null);
        car1.setStatus(car.getStatus());
        carService.update(car1);
      }
      car.setEmployName(null);
    } else if (car.getEmployId() != null) {
      Car car1 = carService.findByEmployId(car.getEmployId(), car.getAppKey());
      if (car1 != null && !car1.getId().equals(car.getId())) {
        car1.setEmployId(null);
        car1.setEmployName(null);
        carService.update(car1);
      }
    }
    if ("-".equals(car.getEmployName())) {
      car.setEmployName(null);
    }

    carService.updateIngoreNull(car);
  }

  @Override
  public Car findByNumber(String carNumber, String appKey) {

    return carService.findByNumber(carNumber, appKey);
  }

  @Override
  public List<Car> findInsuranceTimeOverdue(Long companyId,String appKey) {
    Date date = new Date();
    List<Car> cars = carService.findAllByInsuranceTime(companyId, appKey);
    List<Car> list = new ArrayList<Car>();
    for (Car car : cars) {
      List<Insurance> ins =  insuranceService.findByCarId(car.getId(),car.getAppKey());
      if(!CollectionUtils.isEmpty(ins)){
        car.setInsuranceTime(ins.get(0).getInsuranceEndDate());
      }
      if(car.getInsuranceTime()==null){
        if(!CollectionUtils.isEmpty(ins)){
          car.setInsuranceTime(ins.get(0).getInsuranceEndDate());
        }
      }

      if(car.getInsuranceTime()!=null){
        long day = (car.getInsuranceTime().getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
        if (day <= 30) {
          list.add(car);
        }
      }
    }
    return list;
  }

  @Override
  public List<Car> findOverhaulTimeOverdue(Long companyId, String appKey) {
    Date date = new Date();
    List<Car> cars = carService.findAllByOverhaulTime(companyId,appKey);
    List<Car> list = new ArrayList<Car>();
    for (Car car : cars) {
      long day = (car.getOverhaulTime().getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
      if (day <= 30) {
        list.add(car);
      }
    }
    return list;
  }

  @Override
  public List<Car> findByCarType(CarQuery carQuery) {
    return carService.findByParams(carQuery);
  }

  @Override
  public Car queryByEmployId(Long employId, String appKey) {
    
    return carService.findByEmployId(employId, appKey);
  }

  @Override
  public Car queryCarByNumber(String carNumber, String appKey) {
    
    return carService.queryCarByNumber(carNumber, appKey);
  }
  
  @Override
  public DataGrid<Car> findByParams(CarQuery carQuery) {
    DataGrid<Car> dataGrid = new DataGrid<Car>();
    List<Car> list = carService.findByParams(carQuery);
    Long count = carService.countByParams(carQuery);
    dataGrid.setRows(list);
    dataGrid.setTotal(count);
    return dataGrid;
  }
  
  @Override
  public DataGrid<Car> findByTiaojians(Car2Query car2Query) {
    DataGrid<Car> dataGrid = new DataGrid<Car>();
    List<Car> list = carService.findByTiaojians(car2Query);
    Long count = carService.countByTiaojians(car2Query);
    dataGrid.setRows(list);
    dataGrid.setTotal(count);
    return dataGrid;
  }
  
  @Override
  public Long findByRentalCompanyId(Long rentalCompanyId, String appKey) {
    return carService.findByRentalCompanyId(rentalCompanyId,appKey);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public Map<String, Object> batchCreate(String cars, String appKey) {
    Gson gson = new Gson();
    Map<String,Object>  data = new HashMap<>();
    long carNumber = 0L;
    long typeNumber = 0L;
    List<Car> list = gson.fromJson(cars, new TypeToken<List<Car>>() {}.getType());
    List<CarTypeCompany> carTypeCompanies = carTypeCompanyService.countType(
        list.get(0).getCompanyId(), appKey);
    List<Long> ids = null;
    if (!CollectionUtils.isEmpty(carTypeCompanies)) {
      ids = new LinkedList<>();
      for (CarTypeCompany ctc : carTypeCompanies) {
        ids.add(ctc.getCarTypeId());
      }
    }
    List<CarType> carTypes  = carTypeService.findByIds(ids);
    List<Car> carss = new LinkedList<>();
    for (Car car : list) {
      Car byNumber = findByNumber(car.getCarNumber(), appKey);
      if (byNumber != null) {
        carNumber += 1L;
        continue;
      }
      boolean flag = false;
      for (Car obj : carss) {
        if (obj.getCarNumber().equalsIgnoreCase(car.getCarNumber())) {
          flag = true;
          break;
        }
      }
      if (flag) {
        carNumber += 1L;
        continue;
      }
      flag = true;
      for (CarType ct : carTypes) {
        if (ct.getTypeName().equalsIgnoreCase(car.getCarTypeName())) {
          car.setCarTypeId(ct.getId());
          car.setAppKey(appKey);
          car.setStatus(0);
          car.setLimitLine(0);
          carss.add(car);
          flag = false;
          break;
        }
      }
      if (flag) {
        typeNumber += 1L;
      }
    }
    int rows = carService.batchCreate(carss);
    data.put("carNumber",carNumber);
    data.put("typeNumber",typeNumber);
    data.put("rows",rows);
    return data;
  }

  @Override
  public DataGrid<Car> findByIds(CarQuery carQuery) {
    DataGrid<Car> dataGrid = new DataGrid<Car>();
    List<Car> list = carService.findByIds(carQuery);
    Long count = carService.countByIds(carQuery);
    dataGrid.setRows(list);
    dataGrid.setTotal(count);
    return dataGrid;
  }

  @Override
  public List<Car> updateByIds(Long[] ids, String appKey) {
    return carService.updateByIds(ids,appKey);
  }

  @Override
  public long count(String appKey) {
    return  carService.count(appKey);
  }


@Override
public Car queryCarByNumberAndFlights(String carNumber, String flights,
		String appKey) {
	return carService.queryCarByNumberAndFlights(carNumber,flights, appKey);
}


@Override
public CarType getCarTypeByTypeName(String typeName, String appKey) {
	return carTypeService.getCarTypeByTypeName(typeName,appKey);
}


@Override
public void updateUpStatus(Long id) {
	carService.updateUpStatus(id);
	
}


}
